<template>
    <div class="home">
        <Header></Header>
        <GoodsList
            :list="goodslist"
            :showchecked="checklist"
            @fn1="radcheck"
            @fn3="deletecart"
            @fn4="add1"
        />
        <Footer :ishowallcheck="ishowallcheck" @fn="allcheck" :totalprice="totalprice"></Footer>
    </div>
</template>

<script>
// @ is an alias to /src
import GoodsList from '@/components/GoodsList.vue';
import Header from '@/components/Myheader.vue';
import Footer from '@/components/Myfooter.vue';
import { mapState, mapMutations } from 'vuex';

export default {
    components: {
        GoodsList,
        Header,
        Footer,
    },
    data() {
        return {
            checklist: [],
            ishowallcheck: false,
        };
    },
    computed: {
        ...mapState({
            goodslist: state => state.cart.goodslist,
        }),
        totalprice() {
            let total = this.goodslist.reduce((pre, cur, index) => {
                console.log(this.checklist[index]);
                // console.log(cur.price * cur.num);
                console.log(this.goodslist[index]);
                return pre + (this.checklist[index] ? cur.price * cur.num : 0);
            }, 0);
            return total;
        },
    },
    created() {
        this.checklist = this.goodslist.map(item => (item = false));
        console.log(this.checklist);
    },
    // beforeDestroy() {
    //     localStorage.setItem('goodslist', this.goodslist);
    //     localStorage.setItem('checklist', this.checklist);
    //     localStorage.setItem('ishowallcheck', this.ishowallcheck);
    //     localStorage.setItem('totalprice', this.totalprice);
    // },
    methods: {
        ...mapMutations({
            delete: 'cart/delete',
            add: 'cart/add',
        }),
        allcheck() {
            this.ishowallcheck = !this.ishowallcheck;
            console.log(this.ishowallcheck);
            this.checklist = this.checklist.map(item => (item = this.ishowallcheck));
        },
        radcheck(index) {
            // console.log(index);
            this.$set(this.checklist, index, !this.checklist[index]);
            console.log(this.checklist[index]);
            let arr = this.checklist.filter(item => item == true);
            // console.log(this.checklist.length);
            // console.log(arr.length);
            if (arr.length == this.checklist.length) {
                this.ishowallcheck = true;
            } else {
                this.ishowallcheck = false;
            }
            console.log(this.totalprice);
        },
        deletecart(index) {
            this.delete(index);
        },
        add1(index, val) {
            this.add({ index1: index, val1: val });
        },
    },
};
</script>
